package com.heaven.map.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Calendar;

@Component
public class JWTUtils {
    @Value("${self.jwt.secret}")
    private String secret;
    @Value("${self.jwt.expire}")
    private int expire;

    //获取Token
    public String getToken(String email){
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.HOUR,expire);
        JWTCreator.Builder builder = JWT.create();
        builder.withClaim("email",email);
        String token = builder.withExpiresAt(instance.getTime())
                .sign(Algorithm.HMAC256(secret));
        return token;
    }
    //验证token是否合法并且返回DecodedJWT
    public DecodedJWT verify(String token){
        return JWT.require(Algorithm.HMAC256(secret)).build().verify(token);
    }
}
